<template>
	<view style="background-color: #FFFFFF;">
		<view class="container container-wrap">
			<view class="tbk-section">
				<icon type="clear" size="22" @tap="resetText" class="clear-text-icon"></icon>
				<view class="page-section">
					<view class="page-section-title" style="font-size: 14px;display: inline-flex;">
						如果觉得有用的话，就添加到我的小程序
						<image src="@/static/yindao.png" style="margin-top: -20px;width:32px ;height: 32px;"></image>
					</view>
					<view class="textarea-wrp" style="background-color: #F1F1F1;">
						<textarea placeholder="请输入或者黏贴要转方音的文本" @input="bindTextAreaBlur" :value="text" maxlength="1000" />
					</view>
				</view>
				<view class="section section_gap" style="float: unset;">
					<view style="">
						<view @click="radioChange(item.speakerId)" style="padding: 3px 3px;float: left;" v-for="(item, key) in items" :key="key" :value="item.speakerId">
							<u-avatar :src="item.img"></u-avatar>
							<u-icon v-if="per == item.speakerId" name="checkmark-circle-fill" color="#2979ff" style="margin-left: -10px;"></u-icon>
							<view style="text-align: center;font-size: 9px;">{{ item.speaker }}</view>
							<view style="text-align: center;font-size: 9px;color: #B2B2B2;">{{ item.speechType }}</view>
						</view>
					</view>
				</view>
				<view style=" clear:both;"></view>
				<view class="section section_gap" style="width:100%">
					<view class="body-view">
						<text class="section_title">音量</text>
						<slider @change="sliderSize" :block-size="blockSize" :block-color="blockColor" :activeColor="sliderActiveColor" :value="vol" min="1" max="100" show-value />
					</view>
				</view>
				<view class="section section_gap">
					<view class="body-view">
						<text class="section_title">语速</text>
						<slider
							@change="sliderSpeed"
							:block-size="blockSize"
							:block-color="blockColor"
							:activeColor="sliderActiveColor"
							:value="spd"
							min="-500"
							max="500"
							show-value
						/>
					</view>
				</view>
				<view class="section section_gap">
					<view class="body-view">
						<text class="section_title">语调</text>
						<slider
							@change="sliderHigh"
							:block-size="blockSize"
							:value="pit"
							:block-color="blockColor"
							:activeColor="sliderActiveColor"
							min="-500"
							max="500"
							show-value
						/>
					</view>
				</view>
				<!--<navigator url="/pages/user/user?title=navigate"  hover-class="navigator-hover">跳转到登页面</navigator>-->
			</view>
			<view class="section btn-container">
				<button class="line-btn" @tap="toVoice">转成人声</button>
				<button class="line-btn" @tap="clipLink">复制音频地址</button>
			</view>
			<!-- <view class="section btn-container">
				<button class="line-btn" @tap="toDown">下载mp3</button>
			</view> -->
		</view>
		<view class="section btn-container" style="color: #888888;">更多功能还在开发中...</view>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
let videoAd = null;
import peiyin from '../../common/peiyin.js';
const host = '';
//const host = 'http://127.0.0.1:7008';
let interstitialAd = null;
export default {
	components: {},
	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function(ops) {
		if (ops.from === 'button') {
			// 来自页面内转发按钮
			console.log(ops.target);
		}
		return {
			title: 'Hi~我是配音小助手，可以把文字转成各种语音,你也快来试试~',
			path: 'pages/index/index',
			imageUrl: this.imageUrl + 'images/mini-program-douyin-share-voice.png',
			success: function(res) {
				uni.showToast({
					title: '谢谢您的转发，请收下我的膝盖',
					icon: 'none',
					duration: 1500
				});
			},
			fail: function(res) {}
		};
	},
	data() {
		return {
			items: [],
			per: '',
			spd: 0,
			vol: 50,
			pit: 0,
			text: '',
			voiceSrc: '',
			radioActiveColor: '#10AEFF',
			sliderActiveColor: ' #10AEFF',
			blockSize: 16,
			blockColor: '#1E90FF',
			activeAd: 0,
			postData:{
				text:'',
				volume:'',
				speech_rate:'',
				pitch_rate:'',
				voice:''
			}
		};
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		console.log(options);
		if (!options.scene) {
			options.scene = '通用';
		}
		let items = peiyin.filter(function(item) {
			return item.scene == options.scene;
		});
		this.items = items;

		// 在页面onLoad回调事件中创建插屏广告实例
		if (wx.createInterstitialAd) {
			interstitialAd = wx.createInterstitialAd({
				adUnitId: 'adunit-57eeb02592ab529a'
			});
			interstitialAd.onLoad(() => {});
			interstitialAd.onError(err => {});
			interstitialAd.onClose(() => {});
		}
		const that = this;
		if (wx.createRewardedVideoAd) {
			videoAd = wx.createRewardedVideoAd({
				adUnitId: 'adunit-7e5dacd8f0132913'
			});
			videoAd.onLoad(() => {});
			videoAd.onError(err => {

			});
			videoAd.onClose(res => {
				// 用户点击了【关闭广告】按钮
				if (res && res.isEnded) {
					setTimeout(function(){
						that.$refs.uToast.show({
							title: '感谢您的观看',
							type: 'success',
							duration:1000
						});
						setTimeout(function(){
							that.loadVoice();
						},1000)
					},300)
				} else {
					// 播放中途退出，不下发游戏奖励
					this.$refs.uToast.show({
						title: '请耐心看完广告，感谢您的支持',
						type: 'error',
						duration:2000
					});
				}
			});
		}
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		this.activeAd = 0;
		this.activeAd = 1;
		// 在适合的场景显示插屏广告

		setTimeout(function() {
			console.log(interstitialAd);
			if (interstitialAd) {
				interstitialAd.show().catch(err => {
					console.error(err);
				});
			}
		}, 300);
	},
	methods: {
		toVoice: async function(e) {
			var data = {};
			data.text = this.text;
			data.volume = this.vol;
			data.speech_rate = this.spd;
			data.pitch_rate = this.pit;
			data.voice = this.per;
			this.postData=data;
			if (!this.text) {
				uni.showToast({
					title: '请输入要转换成语音的文本',
					icon: 'none',
					duration: 1500
				});
				return;
			}
			if (!this.per) {
				uni.showToast({
					title: '请选择发音人',
					icon: 'none',
					duration: 1500
				});
				return;
			}


			const that=this;
			// 用户触发广告后，显示激励视频广告
			if (videoAd) {
				videoAd.show().catch(() => {
					// 失败重试
					videoAd.load().then(() => videoAd.show())
						.catch(err => {

							that.loadVoice();


						});
				});
			}




			//console.log(ret);
		},
		toDown: function(e) {
			let downloadUrl = this.voiceSrc;
			if (downloadUrl) {
				uni.downloadFile({
					url: downloadUrl, //仅为示例，并非真实的资源
					success: res => {
						if (res.statusCode === 200) {
							console.log('下载成功');
							uni.showToast({
								title: '下载成功',
								icon: 'success',
								duration: 1000
							});
						}
					}
				});
			}
		},
		async loadVoice(){
			const that=this;
			uni.showLoading({
				title: '加载中'
			});
			try {
				let ret = await this.$u.post(host, this.postData);
				let xx = host + '/public/mp3/' + ret;
				
				uni.hideLoading();
				
				
				
				that.voiceSrc = xx;
				that.playVoice(xx);
			} catch (err) {
				console.log(22, err);
					uni.hideLoading();
				uni.showToast({
					title: '转换失败',
					icon: 'error',
					duration: 1000
				});
			}
		},
		bindTextAreaBlur: function(e) {
			//console.log(e.detail.value);
			this.text = e.detail.value;
		},
		resetText: function(e) {
			this.text = '';
		},
		radioChange: function(val) {
			this.per = val;
			console.log(this.per);
		},
		sliderSize: function(e) {
			this.vol = e.detail.value;
			console.log(this.vol);
		},
		sliderSpeed: function(e) {
			this.spd = e.detail.value;
			console.log(this.spd);
		},
		sliderHigh: function(e) {
			this.pit = e.detail.value;
			console.log(this.pit);
		},
		playVoice: function(src) {
			let audio = uni.createInnerAudioContext();
			audio.obeyMuteSwitch = false;
			audio.src = src;

			console.log(audio.src);

			audio.onPlay(() => {
				console.log('音频播放开始');
			});
			audio.onPause(() => {});
			audio.onWaiting(() => {});
			audio.onStop(() => {});
			audio.onTimeUpdate(() => {});
			audio.onSeeking(() => {});
			audio.onSeeked(() => {});
			audio.onEnded(() => {
				console.log('音频播放结束');
				console.log('销毁音频实例');
				audio.destroy(); //销毁音频实例
				audio = null;
			});
			audio.onError(e => {
				console.log('音频播放错误: ' + JSON.stringify(e));
				console.log('销毁音频实例');
				audio.destroy(); //销毁音频实例
				audio = null;
			});
			audio.play();
		},
		clipLink: function(e) {
			let downloadUrl = this.voiceSrc;
			if (downloadUrl) {
				uni.setClipboardData({
					data: downloadUrl,
					success(res) {
						uni.showToast({
							title: '复制链接成功',
							icon: 'success',
							duration: 1000
						});
					}
				});
			} else {
				this.$refs.uToast.show({
					title: '请先输入文字、然后点击“转成人声”',
					type: 'error'
				});
			}
		}
	}
};
</script>
<style>
.ad-container {
	margin-top: 8upx;
}
page {
	background-color: RGB(245, 245, 245);
}
.container-wrap {
	min-height: 100%;
	padding: 30rpx 5%;
	width: 90%;
}
textarea {
	width: 100%;
	padding: 20rpx 0;
	height: 250rpx;
	font-size: 32rpx;
}
.textarea-wrp {
	padding: 0 25rpx;
	background-color: #fff;
}
.clear-text-icon {
	position: absolute;
	z-index: 2;
	top: 60rpx;
	left: 660rpx;
}

.page-section {
	width: 100%;
	margin-bottom: 60rpx;
}
.section_gap {
	margin: 30rpx 0;
}
.page-section:last-child {
	margin-bottom: 0;
}

.section_title {
	width: 20%;
	font-size: 36rpx;
	line-height: 250%;
	font-weight: 400;
	color: #999999;
}

radio {
	transform: scale(0.8);
}
.radio-text {
	font-size: 36rpx;
	color: #999999;
}
.body-view {
	display: flex;
	height: 50rpx;
}
.body-view slider {
	width: 80%;
}

.page-section-title {
	margin: 20rpx 0;
	font-size: 36rpx;
	font-weight: 400px;
	color: #999999;
	padding-left: 10rpx;
	padding-right: 30rpx;
}
.btn-container {
	display: flex;
	flex-direction: row;
	justify-content: center;
	margin-top: 80rpx;
}
.line-btn {
	margin: 2rpx 50rpx;
	background-color: #1e90ff;
	color: white;
	font-size: 36rpx;
	line-height: 72rpx;
}
</style>
